package net.xdclass.component;

import lombok.extern.slf4j.Slf4j;
import net.xdclass.config.SmsConfig;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

@Component
@Slf4j
public class SmsComponent {

    private static final String SMS_URL = "https://gyyyx1.market.alicloudapi.com/sms/smsSend?mobile=%s&templateId=%s&smsSignId=%s&param=%s";

    @Autowired
    private RestTemplate restTemplate;

    @Autowired
    private SmsConfig smsConfig;

    /**
     * 发送短信验证码
     * @param to
     * @param templateId
     * @param smsSignId
     * @param param
     */
    @Async("threadPoolTaskExecutor")
    public void send(String to, String templateId, String smsSignId, String param){
        String url = String.format(SMS_URL, to, templateId, smsSignId, param);
        HttpHeaders headers = new HttpHeaders();
        headers.set("Authorization", "APPCODE "+smsConfig.getAppCode());
        HttpEntity entity = new HttpEntity(headers);
        ResponseEntity<String> response = restTemplate.exchange(url, HttpMethod.POST, entity, String.class);
        log.info("url={},body={}", url, response.getBody());
        if (response.getStatusCode().is2xxSuccessful()) {
            log.info("发送短信成功，响应信息:{}", response.getBody());
        } else {
            log.error("发送短信失败，响应信息:{}", response.getBody());
        }
    }

}
